/**
 * 扇环标绘工具类
 * 提供交互式扇环标绘功能，支持鼠标绘制、参数调整和样式配置
 */
export default class SectorRingDrawer {
  /**
   * 构造函数
   * @param {Cesium.Viewer} viewer Cesium Viewer实例
   * @param {Object} [options] 配置选项
   * @param {Number} [options.innerRadius=500] 默认内半径（米），减小默认值
   * @param {Number} [options.outerRadius=2000] 默认外半径（米），减小默认值
   * @param {Number} [options.startAngle=0] 默认起始角度（度）
   * @param {Number} [options.endAngle=90] 默认结束角度（度）
   * @param {Object} [options.style] 标绘样式配置
   */
  constructor(viewer, options = {}) {
    // 核心实例
    this.viewer = viewer;

    // 标绘状态管理
    this.state = {
      isDrawing: false,       // 是否正在标绘
      center: null,           // 中心点（Cartesian3）
      innerRadius: options.innerRadius || 500,  // 减小默认内半径
      outerRadius: options.outerRadius || 2000, // 减小默认外半径
      startAngle: options.startAngle || 0,
      endAngle: options.endAngle || 90,
      currentEntity: null,    // 当前标绘实体
      handler: null           // 事件处理器
    };

    // 样式配置（合并默认与用户配置）
    this.style = {
      material: Cesium.Color.RED.withAlpha(0.5), // 增加透明度以便观察
      outline: true,
      outlineColor: Cesium.Color.YELLOW, // 使用更明显的轮廓颜色
      outlineWidth: 3, // 增加轮廓宽度
      ...options.style
    };

    // 调试模式
    this.debugMode = true;
  }

  /**
   * 内部方法：创建扇环实体
   * @param {Cesium.Cartesian3} center 中心点
   * @param {Number} innerRadius 内半径
   * @param {Number} outerRadius 外半径
   * @param {Number} startAngle 起始角度
   * @param {Number} endAngle 结束角度
   * @returns {Cesium.Entity} 扇环实体
   */
  #createSectorRing(center, innerRadius, outerRadius, startAngle, endAngle) {
    if (this.debugMode) {
      console.log('[SectorRingDrawer] Creating sector ring with parameters:', {
        center, innerRadius, outerRadius, startAngle, endAngle
      });
    }

    // 角度转换为弧度
    const startRad = Cesium.Math.toRadians(startAngle);
    const endRad = Cesium.Math.toRadians(endAngle);
    const angleDiff = endRad - startRad;

    // 计算顶点（按1°间隔采样，保证平滑度）
    const points = [];
    const sampleCount = Math.ceil(angleDiff / Cesium.Math.toRadians(1)) + 1;

    // 获取中心点的高度
    const centerCartographic = Cesium.Cartographic.fromCartesian(center);
    const centerHeight = centerCartographic.height;

    if (isNaN(centerHeight)) {
      console.error('[SectorRingDrawer] Invalid height from center point:', center);
      // 尝试使用默认高度
      return this.#createSectorRingWithDefaultHeight(center, innerRadius, outerRadius, startAngle, endAngle);
    }

    // 外圆弧顶点（从结束角度到起始角度，顺时针）
    for (let i = 0; i <= sampleCount; i++) {
      const angle = endRad - (i * angleDiff) / sampleCount;
      const offset = this.#calculateOffset(angle, outerRadius, centerCartographic);
      const position = Cesium.Cartesian3.add(center, offset, new Cesium.Cartesian3());
      const cartographic = Cesium.Cartographic.fromCartesian(position);
      cartographic.height = centerHeight;
      points.push(cartographic);
    }

    // 内圆弧顶点（从起始角度到结束角度，逆时针，闭合多边形）
    for (let i = 0; i <= sampleCount; i++) {
      const angle = startRad + (i * angleDiff) / sampleCount;
      const offset = this.#calculateOffset(angle, innerRadius, centerCartographic);
      const position = Cesium.Cartesian3.add(center, offset, new Cesium.Cartesian3());
      const cartographic = Cesium.Cartographic.fromCartesian(position);
      cartographic.height = centerHeight;
      points.push(cartographic);
    }

    // 创建多边形层级
    const polygonHierarchy = new Cesium.PolygonHierarchy(
      points.map(p => Cesium.Cartesian3.fromRadians(p.longitude, p.latitude, p.height))
    );

    if (this.debugMode) {
      console.log('[SectorRingDrawer] Created polygon hierarchy with',
        polygonHierarchy.positions.length, 'vertices');
    }

    // 创建并返回实体
    const entity = this.viewer.entities.add({
      polygon: {
        hierarchy: polygonHierarchy,
        material: this.style.material,
        outline: this.style.outline,
        outlineColor: this.style.outlineColor,
        outlineWidth: this.style.outlineWidth,
        perPositionHeight: true, // 确保使用每个点的高度
        classificationType: Cesium.ClassificationType.BOTH // 与地形和3D模型交互
      },
      description: `扇环: 内半径=${innerRadius}m, 外半径=${outerRadius}m, 角度=${startAngle}°-${endAngle}°`
    });

    if (this.debugMode && entity) {
      console.log('[SectorRingDrawer] Successfully created entity with ID:', entity.id);
    }

    return entity;
  }

  /**
   * 内部方法：使用默认高度创建扇环实体（当无法获取有效高度时）
   */
  #createSectorRingWithDefaultHeight(center, innerRadius, outerRadius, startAngle, endAngle) {
    console.log('[SectorRingDrawer] Using default height (10m) for sector ring');

    // 创建一个基于中心位置的新Cartesian3，但高度设为10米
    const centerCartographic = Cesium.Cartographic.fromCartesian(center);
    centerCartographic.height = 10;
    const newCenter = Cesium.Cartesian3.fromRadians(
      centerCartographic.longitude,
      centerCartographic.latitude,
      centerCartographic.height
    );

    return this.#createSectorRing(newCenter, innerRadius, outerRadius, startAngle, endAngle);
  }

  /**
   * 内部方法：计算基于角度和距离的偏移量，考虑地形朝向
   */
  #calculateOffset(angle, distance, centerCartographic) {
    // 计算偏移量，考虑地形的朝向（法线方向）
    const normal = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(
      Cesium.Cartesian3.fromRadians(
        centerCartographic.longitude,
        centerCartographic.latitude,
        centerCartographic.height
      )
    );

    // 创建局部坐标系
    const east = Cesium.Cartesian3.cross(
      new Cesium.Cartesian3(0, 0, 1),
      normal,
      new Cesium.Cartesian3()
    );
    Cesium.Cartesian3.normalize(east, east);

    const north = Cesium.Cartesian3.cross(normal, east, new Cesium.Cartesian3());

    // 计算基于角度的偏移
    const x = Math.cos(angle) * distance;
    const y = Math.sin(angle) * distance;

    // 组合偏移
    const offset = new Cesium.Cartesian3();
    Cesium.Cartesian3.multiplyByScalar(east, y, offset);
    const temp = new Cesium.Cartesian3();
    Cesium.Cartesian3.multiplyByScalar(north, x, temp);
    Cesium.Cartesian3.add(offset, temp, offset);

    return offset;
  }

  /**
   * 内部方法：更新标绘预览
   */
  #updatePreview() {
    if (!this.state.center) return;

    // 移除旧实体
    if (this.state.currentEntity) {
      this.viewer.entities.remove(this.state.currentEntity);
      if (this.debugMode) {
        console.log('[SectorRingDrawer] Removed previous entity');
      }
    }

    // 创建新预览实体
    this.state.currentEntity = this.#createSectorRing(
      this.state.center,
      this.state.innerRadius,
      this.state.outerRadius,
      this.state.startAngle,
      this.state.endAngle
    );

    if (!this.state.currentEntity) {
      console.error('[SectorRingDrawer] Failed to create sector ring entity');
    } else {
      // 缩放相机以查看完整的扇环
      // if (this.debugMode) {
      //   this.viewer.zoomTo(this.state.currentEntity);
      // }
    }
  }

  /**
   * 开始标绘
   * 激活鼠标事件监听，进入标绘状态
   */
  startDrawing() {
    if (this.state.isDrawing) return;

    this.state.isDrawing = true;
    this.state.center = null;
    this.state.currentEntity = null;

    // 初始化事件处理器
    this.state.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas);

    // 左键点击设置中心点
    this.state.handler.setInputAction((event) => {
      const ray = this.viewer.camera.getPickRay(event.position);
      const position = this.viewer.scene.globe.pick(ray, this.viewer.scene);

      if (position) {
        this.state.center = position;
        this.#updatePreview();

        if (this.debugMode) {
          const cartographic = Cesium.Cartographic.fromCartesian(position);
          console.log('[SectorRingDrawer] Center point set at:', {
            longitude: Cesium.Math.toDegrees(cartographic.longitude),
            latitude: Cesium.Math.toDegrees(cartographic.latitude),
            height: cartographic.height
          });
        }
      } else {
        console.log('[SectorRingDrawer] Failed to pick position on globe. Click on terrain.');
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 右键点击完成标绘
    this.state.handler.setInputAction(() => {
      this.finishDrawing();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    // 鼠标移动更新角度
    this.state.handler.setInputAction((event) => {
      if (!this.state.center) return;

      const ray = this.viewer.camera.getPickRay(event.endPosition);
      const position = this.viewer.scene.globe.pick(ray, this.viewer.scene);

      if (position) {
        // 计算鼠标位置相对中心点的角度
        const cartographic = Cesium.Cartographic.fromCartesian(position);
        const centerCartographic = Cesium.Cartographic.fromCartesian(this.state.center);

        // 计算经纬度差
        const dx = cartographic.longitude - centerCartographic.longitude;
        const dy = cartographic.latitude - centerCartographic.latitude;

        // 计算距离，用于调试
        const distance = Math.sqrt(dx * dx + dy * dy) * Cesium.Ellipsoid.WGS84.maximumRadius;

        // 转换为正北为0°的顺时针角度
        let angle = Math.atan2(dx, dy) * 180 / Math.PI;
        if (angle < 0) angle += 360;

        // 更新结束角度并刷新预览
        this.state.endAngle = angle;
        this.#updatePreview();

        if (this.debugMode) {
          console.log('[SectorRingDrawer] Mouse move - angle:', angle.toFixed(2), 'degrees, distance:', distance.toFixed(2), 'm');
        }
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    console.log('[SectorRingDrawer] 扇环标绘已启动：左键设置中心点，右键完成绘制');

    // 添加提示信息
    if (this.debugMode) {
      this._addDebugMessage('扇环标绘模式已启动\n左键: 设置中心点\n右键: 完成绘制\n移动鼠标: 调整扇环角度');
    }
  }

  /**
   * 结束标绘
   * 停止事件监听，退出标绘状态，返回标绘结果
   * @returns {Object|null} 标绘结果（包含实体和参数）
   */
  finishDrawing() {
    if (!this.state.isDrawing) return null;

    // 清理事件处理器
    if (this.state.handler) {
      this.state.handler.destroy();
      this.state.handler = null;
    }

    this.state.isDrawing = false;

    // 移除调试信息
    this._removeDebugMessage();

    // 返回标绘结果
    if (this.state.center && this.state.currentEntity) {
      const centerCartographic = Cesium.Cartographic.fromCartesian(this.state.center);
      const result = {
        entity: this.state.currentEntity,
        center: {
          longitude: Cesium.Math.toDegrees(centerCartographic.longitude),
          latitude: Cesium.Math.toDegrees(centerCartographic.latitude),
          height: centerCartographic.height
        },
        innerRadius: this.state.innerRadius,
        outerRadius: this.state.outerRadius,
        startAngle: this.state.startAngle,
        endAngle: this.state.endAngle
      };

      if (this.debugMode) {
        console.log('[SectorRingDrawer] 扇环标绘完成:', result);
      }

      return result;
    }

    console.log('[SectorRingDrawer] 扇环标绘已取消（未设置中心点）');
    return null;
  }

  /**
   * 取消标绘
   * 停止标绘并清理中间结果
   */
  cancelDrawing() {
    if (!this.state.isDrawing) return;

    // 移除预览实体
    if (this.state.currentEntity) {
      this.viewer.entities.remove(this.state.currentEntity);
      this.state.currentEntity = null;
    }

    // 清理事件处理器
    if (this.state.handler) {
      this.state.handler.destroy();
      this.state.handler = null;
    }

    // 移除调试信息
    this._removeDebugMessage();

    // 重置状态
    this.state.isDrawing = false;
    this.state.center = null;

    console.log('[SectorRingDrawer] 扇环标绘已取消');
  }

  /**
   * 设置标绘参数
   * 动态更新扇环的半径、角度等参数
   * @param {Object} params 参数对象
   * @param {Number} [params.innerRadius] 内半径
   * @param {Number} [params.outerRadius] 外半径
   * @param {Number} [params.startAngle] 起始角度
   * @param {Number} [params.endAngle] 结束角度
   */
  setParameters(params) {
    if (params.innerRadius !== undefined) {
      this.state.innerRadius = params.innerRadius;
    }
    if (params.outerRadius !== undefined) {
      this.state.outerRadius = params.outerRadius;
    }
    if (params.startAngle !== undefined) {
      this.state.startAngle = params.startAngle;
    }
    if (params.endAngle !== undefined) {
      this.state.endAngle = params.endAngle;
    }

    // 实时更新预览
    if (this.state.isDrawing && this.state.center) {
      this.#updatePreview();
    }
  }

  /**
   * 获取当前标绘参数
   * @returns {Object} 包含内半径、外半径、起始角度、结束角度的参数对象
   */
  getParameters() {
    return {
      innerRadius: this.state.innerRadius,
      outerRadius: this.state.outerRadius,
      startAngle: this.state.startAngle,
      endAngle: this.state.endAngle
    };
  }

  /**
   * 销毁标绘工具
   * 清理所有事件和实体，释放资源
   */
  destroy() {
    this.cancelDrawing();
    this.viewer = null;
    this.state = null;
    this.style = null;
  }

  /**
   * 内部方法：添加调试信息UI
   */
  _addDebugMessage(message) {
    // 移除之前的调试信息
    this._removeDebugMessage();

    // 创建新的调试信息元素
    const debugElement = document.createElement('div');
    debugElement.id = 'sector-ring-debug-message';
    debugElement.style.position = 'absolute';
    debugElement.style.top = '10px';
    debugElement.style.left = '10px';
    debugElement.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    debugElement.style.color = 'white';
    debugElement.style.padding = '10px';
    debugElement.style.borderRadius = '5px';
    debugElement.style.zIndex = '1000';
    debugElement.style.fontFamily = 'Arial, sans-serif';
    debugElement.style.fontSize = '14px';
    debugElement.textContent = message;

    this.viewer.container.appendChild(debugElement);
    this._debugElement = debugElement;
  }

  /**
   * 内部方法：移除调试信息UI
   */
  _removeDebugMessage() {
    if (this._debugElement && this._debugElement.parentNode) {
      this._debugElement.parentNode.removeChild(this._debugElement);
    }
    this._debugElement = null;
  }
}